package org.JWCB.commom.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.JWCB.common.core.constants.UserConstants;
import org.JWCB.common.core.utils.ThreadLocalUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private static final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject,"createBy",Long.class, userId);
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"updateBy",Long.class,userId);
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject,"updateBy",Long.class,userId);
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
    }

    /**
     * 从ThreadLocal里面获取userId
     * @return userId
     */
    private Long getUserId() {
        return ThreadLocalUtil.get(UserConstants.USER_ID,Long.class);
    }
}
